import React, {Fragment} from 'react';
import {connect} from 'dva'
import {Page} from 'components'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import {
  Row,
  Col,
  Form,
  Radio,
  Icon,
  Modal,
  Popover,
  Select
} from 'antd'
import LwjTrees from 'components/LwjTree'
import GeneralFilter from 'components/Filter/GeneralFilter'
import LwjTable from 'components/LwjTable/LwjTable'
import style from './index.less'
import FilterTree from '../Tree'
import {Link} from 'dva/router'



const FormItem = Form.Item;
const RadioGroup = Radio.Group;
let isAddCart = false;
const Option = Select.Option;
const salesmarkets = ({location, dispatch, salesmarket, mydistributor, loading}) => {

  const {
    productList,
    pagination,
    classifyList,
    detailModal,
    detailUrl,
    searchClassifyKeyword,
    count,
    selectedDistributorId
  } = salesmarket;

  const {
    distributorList
  } = mydistributor;

  // 面包屑
  const breadcrumbList = [
    {
      title: '分销市场',
      href: ''
    }, {
      title: '分销市场'
    }
  ];

  // 类目树结构相关属性
  const ClassifyTreeProps = {
    dataSource: classifyList,
    defaultExpandAll: true,
    showLine: true,
    showIcon: false,
    onSelect: (datum) => {
      dispatch({
        type: 'salesmarket/setClassifyId',
        classifyId: datum.id
      })
      dispatch({
        type: 'salesmarket/query',
        payload: {
          start: 0,
          limit: pagination.pageSize
        }
      })
    },
    onChange: (e) => {
      const value = e.target.value
      dispatch({
        type: 'salesmarket/setClassifySearchKeyword',
        keyword: value
      })
    },
    dispatch,
    searchKeyword: searchClassifyKeyword,
    defaultExpandAll: true
  }

  // 筛选条件
  const filterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'name',
        title: '商品名称'
      }, {
        type: 'input',
        id: 'goods_id',
        title: 'SPU编码'
      }, {
        type: 'input',
        id: 'id',
        title: 'SKU编码'
      }
    ],
    isExpand: true,
    col: 6,
    onFilterChange(value) {
      dispatch({
        type: 'salesmarket/setQueryParam',
        queryParam: value
      })
      dispatch({
        type: 'salesmarket/query',
        payload: {
          limit: pagination.pageSize,
          start: 0
        }
      })
    }
  }


  // 列表相关
  const listProps = {
    dataSource: productList,
    loading: loading.effects['salesmarket/query'],
    pagination,
    pageChangeAction: 'salesmarket/query',
    dispatch,
    location
  }

  //商品列
  const productsColumns = [
    {
      title: 'SPU编码',
      dataIndex: 'goods_id',
      key: 'goods_id',
      width: '10%'
    }, {
      title: 'SKU编码',
      dataIndex: 'id',
      key: 'id',
      width: '10%'
    }, {
      title: '商品图片',
      dataIndex: 'goods_info',
      key: 'goods_info',
      width: '15%',
      render: (text, record) => {
        return (
          <Popover content={<img src={record.goods_info ? record.goods_info.cover_path : ''} className={style.productBigImg} />} title="商品图片" placement="right">
            <img src={record.goods_info ? record.goods_info.cover_path : ''} className={style.productSmallImg} />
          </Popover>
        )
      }
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%',
      render: (text, record, index) => (
        <span>
          <a onClick={() => showProductDetail(record.detail_url)}>{text}</a>
        </span>
      )
    }, {
      title: '零售价',
      dataIndex: 'price',
      key: 'price',
      width: '15%'
    }, {
      title: '渠道价',
      dataIndex: 'channel_price',
      key: 'channel_price',
      width: '10%'
    }, {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: '10%'
    }, {
      title: '操作',
      dataIndex: 'handleType',
      key: 'handleType',
      width: '10%',
      render: (text, record, index) => {
        if(record.has_material){
          return (<span><a onClick={() => addToCart(record)}>加入购物车</a></span>)
        }else{
          return (<span>未绑定物料，暂不能下单</span>)
        }
      }
    }
  ]

  //显示详情弹窗
  const showProductDetail=(detailUrl)=>{
    dispatch({
      type: 'salesmarket/showProductDetail',
      detailUrl
    })
  }

  //详情弹窗属性
  const modalProps={
    title:"详情页",
    visible:detailModal,
    footer:null,
    width: "90%",
    onCancel:()=>{
      dispatch({
        type: 'salesmarket/hideProductDetail'
      })
    },
    style: {top: '24px',bottom: '0px',left: '5%',right: '5%',position: 'fixed', margin: '0px !important'},
    bodyStyle: {position: 'fixed',top: '80px',bottom: '24px',left: '5%',right: '5%',padding: '0px'}
  }

  //加入购物车
  const addToCart=(record)=>{
    if(isAddCart){
      return;
    }
    isAddCart = true;
    setTimeout(function(){
      isAddCart = false;      
    }, 1000);
    dispatch({
      type: 'salesmarket/addToCart',
      item: record
    })
  }

  const handleFormChange = (changedFields = {})=>{
    let queryParam = {};
    for( let key in changedFields){
      queryParam[key] = changedFields[key].value
    }
    dispatch({
      type: 'salesmarket/setQueryParam',
      queryParam: queryParam
    })
  }

  const handleDistributorChange = (val) => {
    dispatch({
      type: 'salesmarket/changeDistributor',
      selectedDistributorId: val
    })
    dispatch({
      type: 'salesmarket/query',
      payload: {
        limit: pagination.pageSize,
        start: 0
      }
    })
    dispatch({
      type: 'salesmarket/queryCartCount'
    })
  }

  return (
    <PageHeaderLayout title="分销市场" breadcrumbList={breadcrumbList}>
      <div className={style.distributor}>
        <div className={style.label}>当前门店</div>
        <Select
          defaultValue={selectedDistributorId}
          onChange={handleDistributorChange}
          showSearch
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          className={style.selectBox}
          dropdownClassName={style.dropDownBox}
        >
          <Option key='-1'>请选择</Option>
          {distributorList.map((distributor) => <Option key={distributor.id}>{distributor.name}</Option>)}
        </Select>
      </div>
      <Page inner>
        <Row gutter={50}>
          <Col span={5} style={{maxHeight: '1400px', overflowY: 'auto'}}>
            {classifyList && classifyList.length > 0 ? <FilterTree {...ClassifyTreeProps}/> : null}
          </Col>
          <Col span={19}>
              <GeneralFilter {...filterProps}  onChange={handleFormChange}/>

              <LwjTable {...listProps} columns={productsColumns}/>

              <Modal {...modalProps}>
                <iframe style={{width:'100%',border: '0px',height: '100%'}} src={detailUrl}></iframe>
              </Modal>
          </Col>
        </Row>
      </Page>
      <div className={style.cart} style={{position:'fixed',right:'20px',bottom:'20px',fontSize:'40px',color:'#33bdb8',zIndex: 100,backgroundColor: '#fff',boxShadow:'0px 0px 2px rgba(0,0,0,0.8',borderRadius: '100%',width: '60px',height: '60px'}}>
        <Link to={selectedDistributorId != '-1' ? "/salesmarket/cartList?id="+selectedDistributorId : "/salesmarket/cartList"}>
          <Icon style={{cursor: 'pointer'}} type="shopping-cart" theme="outlined" />
        </Link>
        <span className={style.cartNum}>{count}</span>
      </div>
    </PageHeaderLayout>
  )
};

export default connect(({salesmarket, mydistributor, loading}) => ({salesmarket, mydistributor, loading}))(salesmarkets)
